package org.lzy.shop.viewmodel.repository.lmpl

import android.content.Context
import android.net.Uri
import kotlinx.coroutines.withTimeoutOrNull
import org.lzy.shop.datas.FeedBackSubmitRequest
import org.lzy.shop.network.KtorApiService
import org.lzy.shop.response.FeedBackItem
import org.lzy.shop.response.FeedbackType
import org.lzy.shop.response.OssUpload
import org.lzy.shop.viewmodel.repository.BaseRepository
import org.lzy.shop.viewmodel.repository.FeedbackRepository

class FeedbackRepositoryImpl : BaseRepository(), FeedbackRepository {

    override suspend fun getFeedbackTypes(): MutableList<FeedbackType>? {
        return safeApiCall {
            val response = KtorApiService.getReasonFeedBack()
            handleResponse(response).feedbackType
        }
    }

    override suspend fun getFeedbackList(page: Int): MutableList<FeedBackItem>? {
        return safeApiCall {
            val response = KtorApiService.getFeedBack(page)
            handleResponse(response).list
        }
    }

    override suspend fun getUploadCredentials(): OssUpload? {
        return withTimeoutOrNull(15000) {
            safeApiCall {
                val response = KtorApiService.getUploadCredentials()
                handleResponse(response)
            }
        }
    }

    override suspend fun uploadImage(
        context: Context,
        imageUri: Uri,
        uploadUrl: String,
        tmpSecretId: String,
        tmpSecretKey: String,
        sessionToken: String
    ): String? {
        return withTimeoutOrNull(30000) {
            safeApiCall {
                val response = KtorApiService.uploadImageToTencent(imageUri, uploadUrl, tmpSecretId, tmpSecretKey, sessionToken)
                handleResponse(response)
            }
        }
    }

    override suspend fun uploadImages(
        context: Context,
        imageUris: List<Uri>,
        uploadUrl: String,
        tmpSecretId: String,
        tmpSecretKey: String,
        sessionToken: String
    ): List<String>? {
        return withTimeoutOrNull(60000) {
            safeApiCall {
                val response = KtorApiService.uploadImagesToTencent(imageUris, uploadUrl, tmpSecretId, tmpSecretKey, sessionToken)
                handleResponse(response) ?: emptyList()
            }
        }
    }

    override suspend fun submitFeedback(request: FeedBackSubmitRequest): Any? {
        return safeApiCall {
            val response = KtorApiService.feedbackSubmit(request)
            handleResponse(response)
        }
    }
}